package timeitj.ejb.projects;

import java.util.ArrayList;
import java.util.List;
import javax.annotation.security.DeclareRoles;
import javax.annotation.security.RolesAllowed;
import javax.ejb.Stateless;
import javax.persistence.NoResultException;
import org.apache.log4j.Logger;
import timeitj.ejb.persistence.PersistenceManagerAbstract;
import timeitj.persistence.Person;
import timeitj.persistence.Project;

/**
 *
 * @author basti
 */
@DeclareRoles({"USERS","ADMINS"})
@Stateless()
public class ProjectManagerBean extends PersistenceManagerAbstract<Project, Long> implements ProjectManager {
    
    public ProjectManagerBean(){
        log = Logger.getLogger(ProjectManagerBean.class.getName());
        log.debug("ProjectManagerBean instantiated");
    }
    
    @RolesAllowed("USERS")
    public List<Project> getProjectsByOwner(Person owner) {
        
        List<Project> ownersProjects;
        
        try {
            ownersProjects =
                    (ArrayList<Project>) em.createNamedQuery("ProjectsByOwner")
                    .setParameter("projectOwner", owner)
                    .getResultList();
            
            
        } catch (NoResultException ex) {
            return null;
        }
        
        return ownersProjects;
    }
    
    @RolesAllowed("USERS")
    public void delete(Project project) {
//        log.info("Deleting Project '" + project.getName() + "'");
        project.getOwner().removeOwnedProject(project);
        super.delete(project);
//        log.info("Done.");
    }
    
}